package org.dingyom.car.service.impl;

import org.dingyom.basics.constants.BaseConstants;
import org.dingyom.basics.service.IBaiduAiService;
import org.dingyom.basics.service.IFastDfsService;
import org.dingyom.basics.util.AjaxResult;
import org.dingyom.basics.util.LoginContext;
import org.dingyom.basics.util.VelocityUtils;
import org.dingyom.car.domain.*;
import org.dingyom.car.dto.CarOprDto;
import org.dingyom.car.es.doc.CarDoc;
import org.dingyom.car.es.repository.CarDocRepository;
import org.dingyom.car.mapper.*;
import org.dingyom.car.service.ICarService;
import org.dingyom.basics.service.impl.BaseServiceImpl;
import org.dingyom.org.domain.Shop;
import org.dingyom.org.domain.ShopAuditLog;
import org.dingyom.org.mapper.ShopMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dingyom
 * @since 2022-09-08
 */
@Service
public class CarServiceImpl extends BaseServiceImpl<Car> implements ICarService {
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private CarDetailMapper carDetailMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private CarTypeMapper carTypeMapper;
    @Autowired
    private CarOnlineAuditLogMapper logMapper;
    @Autowired
    private CarResourcesMapper resourcesMapper;
    @Autowired
    private IBaiduAiService baiduAiService;
    @Autowired
    private CarDocRepository carDocRepository;
    @Autowired
    private IFastDfsService fastDfsService;
    @Override
    public void delete(Serializable id) {
        //删除车辆信息 详细信息 fastdfs中的数据  日志更新出删除的日志
        Car car = carMapper.loadById(id);
        CarResources carResources = resourcesMapper.loadByCarId((Long) id);
        /*fastdfs中的数据*/
        //cover
        String covers = car.getCover();
        if (covers != null) {
            deleteFastdfs(covers);
        }
        //资源中的 img viceimg moreimg
        if (carResources != null) {
            String imgs = carResources.getImg();
            if (imgs != null) {
                deleteFastdfs(imgs);
            }
            String viceimgs = carResources.getViceimg();
            if (viceimgs != null) {
                deleteFastdfs(viceimgs);
            }
            String moreimgs = carResources.getMoreimg();
            if (moreimgs != null) {
                deleteFastdfs(moreimgs);
            }
        }

        carMapper.remove(id);//删除车辆信息
        carDetailMapper.removeByCarId(id);//删除车辆详细信息
        resourcesMapper.removeByCardId((Long)id);//删除车辆资源信息

        //记录删除的日志信息
        CarOnlineAuditLog log = new CarOnlineAuditLog();
        log.setCarId(car.getId());//删除的车辆id
        log.setState(-2);//-2表示已经删除
        log.setAuditId(LoginContext.getLoginUser().getId());//删除人员就是当前登陆用户
        log.setAuditTime(new Date());//删除的时间
        log.setNote("id为"+car.getId()+"的车辆信息已删除");
        logMapper.save(log);
    }

    /**
     * 删除fastdfs中的数据
     * @param paths
     */
    private void deleteFastdfs(String paths) {
        String[] list = paths.split(",");
        for (String path :
                list) {
            fastDfsService.delete(path);
        }
    }

    /**
     * 正常人思维顺序就是 先保存车辆信息获取到自增id 再去保存车辆详细信息
     * 再审核，根据审核结果更改车辆审核装填 需要更新车辆数据
     * 非正常思维，先审核 获取结果，然后准备好车辆信息，详细信息 和日志数据
     * 再去保存车辆信息 详细信息 和 日志信息  这样可以节省一个更新的访问数据库操作
     * @param car
     */
    @Override
    public void add(Car car) {
        CarDetail carDetail = car.getCarDetail();
        /*自动审核 会根据审核结果修改 店铺状态 并添加 审核日志*/
        //审核的内容 文本审核内容-车辆标题 车辆详细信息中的info 图片内容 封面 cover
        String auditTest = car.getTitle()+""+carDetail.getInfo();
        AjaxResult ajaxResult = baiduAiService.audit(auditTest, car.getCover(), null);
        CarOnlineAuditLog log = new CarOnlineAuditLog();  //审核日志() 上下线日志
        if (ajaxResult.isSuccess()){//审核通过
            //车辆审核状态
            car.setAuditstate(1);
            //日志状态 1表示审核通过
            log.setState(1);
            log.setNote("系统审核通过");
        }else{//审核不通过
            //车辆审核状态
            car.setAuditstate(-1);
            //日志状态 -1表示审核不过
            log.setState(-1);
            log.setNote("系统审核失败");
        }
        //保存car 的信息
        car.setCreatetime(new Date());
        car.setState(0L);
        carMapper.save(car);//返回自增主键

        //保存车辆详细信息
        carDetail.setCarId(car.getId());
        carDetail.setCartitle(car.getTitle());
//        accidentInvestigation;
//        coreComponentsInvestigation;
//        commonFunctionsInvestigation;
//        appearanceInspection;
        carDetailMapper.save(carDetail);

        log.setCarId(car.getId());//获取返回的car信息 id
        log.setAuditTime(new Date());
        //系统审核 没有审核人
        logMapper.save(log);

    }

    @Override
    @Transactional
    public void onsale(CarOprDto carOprDto) {
        //参数判断
        List<Long> ids = carOprDto.getIds();
        if (ids == null||ids.size()<1) {
            throw new RuntimeException("系统异常，参数不对！");
        }
        //往elasticsearch中添加数据
        List<CarDoc> carDocs = buildCarDocs(ids);
        carDocRepository.saveAll(carDocs);//批量添加

        //修改数据库的中数据的状态 和上架时间
        carMapper.onsale(ids);//新玩法 在mapper中修改数据
        //添加日志 2表示上架日志
        savelogs(carOprDto,2);

        //车辆上架的同时还要生成车辆详情的静态页面
        staticPage(ids);

    }

    @Value("${static.page.path}")
    private String staticPagePath;//静态页面生成路径
    private void staticPage(List<Long> ids) {
        ids.forEach(id->{//每个id所对应的car信息都要查询出来
            Car car = carMapper.loadById(id);

            //获取模板路径
            String templatePath = this.getClass().getClassLoader().getResource("").getPath() + "/templates/carDetail.vm";
//            System.out.println(templatePath);

            //静态页面生成路径 改成可配置属性
//            String staticPagePath = "D:\\java1\\IdeaProjects\\dingyom-car-websites\\dingyom-car-portal\\details\\";

            String htmlFilePath = staticPagePath + id + ".html";

            VelocityUtils.staticByTemplate(car, templatePath, htmlFilePath);

        });
    }

    private List<CarDoc> buildCarDocs(List<Long> ids) {
        List<CarDoc> result = new ArrayList<>();
        ids.forEach(carId->{
            result.add(buildCarDoc(carId));
        });
        return result;
    }

    /**
     * 创建车辆文档对象
     * @param carId
     * @return
     */
    private CarDoc buildCarDoc(Long carId) {
        //重数据库中获取车辆信息
        Car car = carMapper.loadById(carId);

        //封装成esdoc对象
        CarDoc carDoc = new CarDoc();
        carDoc.setId(carId);
        carDoc.setTitle(car.getTitle());
        carDoc.setCover(car.getCover());
        carDoc.setSaleprice(car.getSaleprice());
        carDoc.setCostprice(car.getCostprice());
        carDoc.setIsnew(car.getIsnew());
        carDoc.setReigstertime(car.getReigstertime());
        carDoc.setMileage(car.getMileage());
        Shop shop = shopMapper.loadById(car.getShopId());
        carDoc.setShopId(shop.getId());
        carDoc.setShopName(shop.getName());
        carDoc.setShopAdress(shop.getAddress());
        carDoc.setOnsaletime(car.getOnsaletime());
        carDoc.setCosteffective(car.getCosteffective());
        carDoc.setRushsale(car.getRushsale());
        carDoc.setQuasinewcar(car.getQuasinewcar());
        carDoc.setTransitivecountry(car.getTransitivecountry());
        CarType carType = carTypeMapper.loadById(car.getTypeId());
        carDoc.setTypeId(carType.getId());
        carDoc.setTypeName(carType.getName());
        //车辆详细信息
        CarDetail detail = carDetailMapper.loadByCarId(carId);
        if (detail!=null)
            carDoc.setCarInfo(detail.getInfo());

        return carDoc;
    }

    @Override
    public void offsale(CarOprDto carOprDto) {
        //判断参数
        List<Long> ids = carOprDto.getIds();
        if (ids == null||ids.size()<1) {
            throw new RuntimeException("系统异常，参数不对！");
        }
        //删除es中的数据
        /*根据id们删除--不可行
        * 封装成carDoc的集合 里面只设置id就行了*/
        List<CarDoc> carDocs = new ArrayList<>();
        ids.forEach(id->{
            CarDoc carDoc = new CarDoc();
            carDoc.setId(id);
            carDocs.add(carDoc);
        });
        carDocRepository.deleteAll(carDocs);
        //修改状态 和获取当前时间
        carMapper.offsale(ids);
        //生成日志 3表示下架日志
        savelogs(carOprDto, 3);
    }

    /**
     * 添加日志 上架和下架都需要添加日志，
     * @param carOprDto 日志所需信息
     * @param state 日志状态 2表示上架 3表示下架
     */
    private void savelogs(CarOprDto carOprDto, int state) {
        List<CarOnlineAuditLog> logs = new ArrayList<>();
        carOprDto.getIds().forEach(id -> {
            CarOnlineAuditLog log = new CarOnlineAuditLog();
            log.setCarId(id);
            log.setState(state);//2表示上架 3表示下架
            log.setAuditId(carOprDto.getOperatorId());
            log.setAuditTime(new Date());
            if (state==2)
                log.setNote(carOprDto.getOperatorName() + "对id为" + id + "的车辆，进行了上架！");
            else if (state==3)
                log.setNote(carOprDto.getOperatorName() + "对id为" + id + "的车辆，进行了下架！");
            logs.add(log);
        });

        logMapper.bulkSave(logs);
    }
}
